﻿using System;
using Service4u2.Common;
using System.Diagnostics;

#if SILVERLIGHT
using System.Windows;
#endif

namespace Service4u2.Xml
{
    public class BaseXmlService<TResultType> : BaseDataService<TResultType>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseXmlService&lt;TResultType&gt;"/> class.
        /// </summary>
        public BaseXmlService()
        {
                
        }

        protected override void HandleResultString(string downloadedString)
        {
            // Check for html doctype and report error if found.
            int takeLength = downloadedString.Length > 20 ? 20 : downloadedString.Length;
            if (downloadedString.Substring(0, takeLength).ToLower().Contains("!doctype html"))
            {
                HandleError(new NotSupportedException("The service call returned html and not xml"));
                return;
            }

            var result = default(TResultType);

            try
            {
                Debug.WriteLine("Service4u2: XML Response: \r\n{0}", downloadedString);
                result = XmlHelper.Deserialize<TResultType>(downloadedString);
            }
            catch(Exception ex)
            {
                HandleError(ex);
                return;
            }           

#if SILVERLIGHT
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                OnGotResult(result));
#else
            OnGotResult(result);
#endif
        }
    }
}
